<template>
  <el-upload
    ref="upload"
    v-model:file-list="formInline.articlePictureUp"
    action="#"
    :limit="1"
    :on-change="handleBeforeUpload"
    :on-exceed="handleExceed"
    :auto-upload="false"
    :show-file-list="false"
    :file-list="['doc', 'docx', 'pdf', 'jpg', 'jpeg', 'png', 'zip', 'rar']"
  >
    <template #trigger>
      <el-input
        placeholder="请选择文件"
        readonly
        style="width: 392px"
        v-model="fileName"
      ></el-input>
    </template>
  </el-upload>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'
import { genFileId } from 'element-plus'
const upload = ref()
// 定义单个 string 类型的 props
const props = defineProps({ modelValue: String })

const emit = defineEmits(['update:modelValue'])

const formInline = ref({ articlePictureUp: props.modelValue ? [{ url: props.modelValue }] : [] })
const fileName = ref('')
watch(
  () => props.modelValue,
  (newVal) => {
    formInline.value.articlePictureUp = newVal ? [{ url: newVal }] : []
  }
)

const handleBeforeUpload = (file) => {
  // 可以在这里使用传入的单个 string 字段
  const isLt5M = file.size / 1024 / 1024 < 50
  if (!isLt5M) {
    ElMessage.error('上传文件大小不能超过 50MB!')
    return false
  }
  const reader = new FileReader()
  console.log('传入的单个字符串字段:', props.singleString)
  fileName.value = file.name
  reader.onload = (e) => {
    emit('update:modelValue', e.target.result)
    emit('fileChange', { name: file.name })

    formInline.value.articlePictureUp = [{ url: e.target.result }]
  }
  reader.readAsDataURL(file.raw)
}
const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}
</script>

<style scoped>
/* 样式部分 */
</style>
